//
//  TAlert.swift
//  TalkeApp
//
//  Created by lhf on 2024/3/8.
//

import Foundation
import UIKit

extension UIAlertController {
    func showAlert(title: String = "", message: String = "", completion: @escaping () -> Void) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
//        let subview1 = alertController.view.subviews.first! as UIView // UIView
//        let subview2 = subview1.subviews.first! as UIView // UIAlertControllerInterfaceActionGroupView
//        let subview3 = subview2.subviews.first! as UIView // UIDimmingKnockoutBackdropView
//        let subview4 = subview3.subviews.first! as UIView // UIVisualEffectView
//        let subview5 = subview4.subviews.first! as UIView // UIVisualEffectBackdropView
//        subview5.backgroundColor = UIColor.white
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        cancelAction.setValue(UIColor.lightGray, forKey: "titleTextColor")
        alertController.addAction(cancelAction)

        let otherAction1 = UIAlertAction(title: "确定", style: .default) { (action) in
            completion()
        }
        otherAction1.setValue(AppConfig.sharedInstance.MAIN_COLOR, forKey: "titleTextColor")
        alertController.addAction(otherAction1)
        
        var count: UInt32 = 0
        // class_copyIvarList: 类的所有属性和变量(包括在@interface大括号中声明的变量)
        // class_copyPropertyList: 对象类的属性(@property申明的属性)
        let properties = class_copyIvarList(UIAlertController.self, &count)
        
        for i in 0..<Int(count) {
            let property = properties![i]
            
            // 取得属性名
            let name = ivar_getName(property)
            print(String(cString: name!))
        }
        
        // object_setIvar: void object_setIvar(id obj, Ivar ivar, id value) 该函数的作用是将实例obj的实例变量ivar赋值为value
        // 修改title
        object_setIvar(alertController, properties![1], NSMutableAttributedString(string: title, attributes: [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: .medium),
            NSAttributedString.Key.foregroundColor: AppConfig.sharedInstance.MAIN_TITLE_COLOR
        ]));
        
        // 修改message
        object_setIvar(alertController, properties![2], NSMutableAttributedString(string: message, attributes: [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: .regular),
            NSAttributedString.Key.foregroundColor: AppConfig.sharedInstance.MAIN_TITLE_COLOR
        ]));
        
        UtilManager.sharedInstance.getCurrentVc().present(alertController, animated: true, completion: nil)
    }
}
